﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using Coevery.ViewModel;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Shell;

namespace Coevery.PhoneApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Popup _popup;
        public MainPage()
        {
            InitializeComponent();
            InitialUsernameAndPassword();
        }

        private void InitialUsernameAndPassword()
        {
            if (App.Setting.Contains("Username") && App.Setting.Contains("Password"))
            {
                textUsername.Text = App.Setting["Username"].ToString();
                textPasswordBox.Password = App.Setting["Password"].ToString();
            }
        }

        private void Login_Click(object sender, EventArgs e)
        {
            SetApplicationBarIconButtonEnabled(false);
            if (string.IsNullOrEmpty(textUsername.Text) || string.IsNullOrEmpty(textPasswordBox.Password))
            {
                MessageBox.Show("The username and password cannot be empty.");
                SetApplicationBarIconButtonEnabled(true);
            }
            else
            {
                _popup = _popup ?? new Popup {Child = new PopuWait()};
                _popup.IsOpen = true;
                //BaseViewModel.Context.Credentials = new NetworkCredential(textUsername.Text, textPasswordBox.Password);
                //SetCookie();

                App.Setting["Username"] = textUsername.Text;
                this._popup.IsOpen = false;
                SetApplicationBarIconButtonEnabled(true);
                NavigationService.Navigate(new Uri("/Index.xaml", UriKind.Relative));
            }
        }

        private void SetApplicationBarIconButtonEnabled(bool IsEnabled)
        {
            foreach (ApplicationBarIconButton item in ApplicationBar.Buttons)
            {
                item.IsEnabled = IsEnabled;
            }
        }

        private void SetCookie()
        {
            if (BaseViewModel.Cookie == null)
            {
                var loginServiceAddress =
                    string.Format("{0}/{1}/{2}",
                    "http://api.coevery.com/coevery",
                    "Authentication_JSON_AppService.axd",
                    "Login");
                var request = CreateAuthRequest(loginServiceAddress);
                request.BeginGetRequestStream(GetRequestStreamCallback, request);
            }
        }

        private WebRequest CreateAuthRequest(string loginServiceAddress)
        {
            var request = (HttpWebRequest)WebRequest.Create(loginServiceAddress);
            request.Method = "POST";
            request.ContentType = "application/json";
            return request;
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            var request = (HttpWebRequest)asynchronousResult.AsyncState;
            var postStream = request.EndGetRequestStream(asynchronousResult);
            var creds = BaseViewModel.Context.Credentials as NetworkCredential;
            if (creds != null)
            {
                var body = string.Format(
                    "{{ \"userName\": \"{0}\", \"password\": \"{1}\", \"createPersistentCookie\":true}}",
                    creds.UserName,
                    creds.Password);
                var streamWriter = new StreamWriter(postStream);
                streamWriter.Write(body);
                streamWriter.Close();
            }
            postStream.Close();
            request.BeginGetResponse(GetResponseCallback, request);
        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            var request = (HttpWebRequest)asynchronousResult.AsyncState;
            var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            if (response.Headers["Set-Cookie"] != null)
            {
                var cookie = response.Headers["Set-Cookie"];
                BaseViewModel.Cookie = cookie;

                Dispatcher.BeginInvoke(() =>
                                            {
                                                if (chbRememberMe.IsChecked != null && chbRememberMe.IsChecked.Value)
                                                {
                                                    App.Setting["Username"] = textUsername.Text;
                                                    App.Setting["Password"] = textPasswordBox.Password;
                                                }
                                                else
                                                {
                                                    if (App.Setting.Contains("Username") && App.Setting.Contains("Password"))
                                                    {
                                                        App.Setting["Username"] = null;
                                                        App.Setting["Password"] = null;
                                                    }
                                                }
                                                this._popup.IsOpen = false;
                                                SetApplicationBarIconButtonEnabled(true);
                                                NavigationService.Navigate(new Uri("/Index.xaml", UriKind.Relative));
                                            });
            }
            else
            {
                Dispatcher.BeginInvoke(() => { _popup.IsOpen = false; MessageBox.Show("The username or password provided is incorrect."); SetApplicationBarIconButtonEnabled(true); });
            }
            response.Close();
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutUs.xaml",UriKind.Relative));

        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to exit?", "Info", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                e.Cancel = false;
            }
            else 
            {
                e.Cancel = true;
            }
        }
    }
}